//
//  AnimationViewController.m
//  Camera
//
//  Created by gml on 2018/10/16.
//  Copyright © 2018年 gml. All rights reserved.
//

#import "AnimationViewController.h"
#import "BaseAnimationViewController.h"

@interface AnimationViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    NSArray *_dataArray;
}
@property (strong, nonatomic) IBOutlet UIView *redView;
@property (nonatomic,strong) CALayer *colorLayer;


@end

@implementation AnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self configData];
    
}
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

-(void)configData{
    NSArray *array_1 = [NSArray arrayWithObjects:@"位移",@"透明度",@"缩放",@"旋转",@"背景色",@"关键帧",@"路径",@"抖动",@"进度条",nil];
    NSMutableDictionary *dic_1 = [NSMutableDictionary dictionaryWithObject:array_1 forKey:@"value"];
    [dic_1 setValue:@"动画" forKey:@"title"];
    _dataArray = @[dic_1];
    [_tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = _dataArray[section];
    NSArray *array = dic[@"value"];
    return array.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSDictionary *dic = _dataArray[section];
    return dic[@"title"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellid = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (nil == cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    cell.textLabel.text = _dataArray[indexPath.section][@"value"][indexPath.row];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        BaseAnimationViewController *vc = [[BaseAnimationViewController alloc] initWithType:indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}









- (void)pan:(UIPanGestureRecognizer *)pan
{
    //get horizontal component of pan gesture
    CGFloat x = [pan translationInView:self.view].x;
    //convert from points to animation duration //using a reasonable scale factor
    x /= 200.0f;
    //update timeOffset and clamp result
    CFTimeInterval timeOffset = self.colorLayer.timeOffset;
    timeOffset = MIN(0.999, MAX(0.0, timeOffset - x));
    self.colorLayer.timeOffset = timeOffset;
    NSLog(@"timeOffset = %f",timeOffset);
    //reset pan gesture
    [pan setTranslation:CGPointZero inView:self.view];
}

- (void)test2
{
    // 1
    //    //create a new transform
    //    CGAffineTransform transform = CGAffineTransformIdentity;
    //    //scale by 50%
    //    transform = CGAffineTransformScale(transform, 0.5, 0.5);
    //    //rotate by 30 degrees
    //    transform = CGAffineTransformRotate(transform, M_PI / 180.0 * 30.0);
    //    //translate by 200 points
    //    transform = CGAffineTransformTranslate(transform, 200, 0);
    //    //apply transform to layer
    //    self.redView.layer.affineTransform = transform;
    
    // 2
    //    CATransform3D transform = CATransform3DMakeRotation(M_PI_4, 0, 1, 0);
    //    self.redView.layer.transform = transform;
    
    // 3
    //    CATransform3D transform = CATransform3DIdentity;
    //    //apply perspective
    //    transform.m34 = - 1.0 / 500.0;
    //    //rotate by 45 degrees along the Y axis
    //    transform = CATransform3DRotate(transform, M_PI_4, 0, 1, 0);
    //    //apply to layer
    //    self.redView.layer.transform = transform;
    
    // 4
  
    //    CALayer *maskLayer = [CALayer layer];
    //    maskLayer.frame = self.redView.bounds;
    //    UIImage *maskImage = [UIImage imageNamed:@"右后黑"];
    //    maskLayer.contents = (__bridge id)maskImage.CGImage;
    //
    //    //apply mask to image layer￼
    //    self.redView.layer.mask = maskLayer;
    
    /*
     //创建一个蓝色的Layer
     CALayer *foregroundLayer        = [CALayer layer];
     foregroundLayer.bounds          = CGRectMake(0, 0, 100, 100);
     foregroundLayer.backgroundColor = [UIColor redColor].CGColor;
     
     //创建一个路径
     UIBezierPath *apath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(20, 20, 60, 60)];
     
     //创建maskLayer
     CAShapeLayer *maskLayer = [CAShapeLayer layer];
     maskLayer.path = apath.CGPath;
     maskLayer.fillColor = [UIColor greenColor].CGColor;
     maskLayer.fillRule = kCAFillRuleEvenOdd;
     
     //设置位置
     foregroundLayer.position = self.view.center;
     //设置mask
     UIImage *maskImage = [UIImage imageNamed:@"右后"];
     //给图层的contents添加内容
     foregroundLayer.contents = (__bridge id)maskImage.CGImage;
     //    foregroundLayer.mask = maskLayer;
     [self.view.layer addSublayer:foregroundLayer];
     
     */
    
    //    self.colorLayer = [CALayer layer];
    //    self.colorLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
    //    self.colorLayer.backgroundColor = [UIColor blueColor].CGColor;
    //    //add a custom action
    //    CATransition *transition = [CATransition animation];
    //    transition.type = kCATransitionPush;
    //    transition.subtype = kCATransitionFromBottom;
    //    self.colorLayer.actions = @{@"backgroundColor": transition};
    //    //add it to our view
    //    [self.redView.layer addSublayer:self.colorLayer];
    
    //    self.colorLayer = [CALayer layer];
    //    self.colorLayer.frame = CGRectMake(50, 50, 100, 100);
    ////    self.colorLayer.position = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
    //    self.colorLayer.backgroundColor = [UIColor blueColor].CGColor;
    //    [self.redView.layer addSublayer:self.colorLayer];
    
    
    self.redView = [[UIView alloc] initWithFrame:CGRectMake(10, 100, [UIScreen mainScreen].bounds.size.width-20, ([UIScreen mainScreen].bounds.size.width-20))];
    self.redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.redView];
    CALayer *doorLayer = [CALayer layer];
    doorLayer.frame = CGRectMake(0, 0, 128, 256);
    doorLayer.position = CGPointMake(150 - 64, 150);
    doorLayer.anchorPoint = CGPointMake(0, 0.5);
    doorLayer.contents = (__bridge id)[UIImage imageNamed: @"右后黑"].CGImage;
    [self.redView.layer addSublayer:doorLayer];
    //apply perspective transform
    CATransform3D perspective = CATransform3DIdentity;
    perspective.m34 = -1.0 / 500.0;
    self.redView.layer.sublayerTransform = perspective;
    //apply swinging animation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.y";
    animation.toValue = @(-M_PI_2);
    animation.duration = 2.0;
    //    animation.repeatDuration = INFINITY;
    //    animation.autoreverses = YES;
    [doorLayer addAnimation:animation forKey:nil];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];
    [pan addTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    
}

- (void)test1
{
    UIImageView *layerView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    layerView1.backgroundColor = [UIColor whiteColor];
    layerView1.layer.shadowOpacity = 0.5f;
    
    //给ImageView添加图像
    layerView1.image = [UIImage imageNamed:@"右后黑"];
    //创建maskLayer
    CALayer *maskLayer = [CALayer layer];
    //给maskLayer 设定frame
    maskLayer.frame = layerView1.bounds;
    
    UIImage *maskImage = [UIImage imageNamed:@"遮罩副本"];
    //给图层的contents添加内容
    maskLayer.contents = (__bridge id)maskImage.CGImage;
    
    //    layerView1.layer.mask = maskLayer;
    
    
    [self.view addSubview:layerView1];
}

-(void)test3
{
    [CATransaction begin];
    //set the animation duration to 1 second
    [CATransaction setAnimationDuration:1.0];
    [CATransaction setCompletionBlock:^{
        //rotate the layer 90 degrees
        CGAffineTransform transform = self.colorLayer.affineTransform;
        transform = CGAffineTransformRotate(transform, M_PI_2);
        self.colorLayer.affineTransform = transform;
    }];
    //randomize the layer background color
    CGFloat red = arc4random() / (CGFloat)INT_MAX;
    CGFloat green = arc4random() / (CGFloat)INT_MAX;
    CGFloat blue = arc4random() / (CGFloat)INT_MAX;
    self.colorLayer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
    [CATransaction commit];
}
- (void)test4
{
    //create a path
    UIBezierPath *bezierPath = [[UIBezierPath alloc] init];
    [bezierPath moveToPoint:CGPointMake(0, 150)];
    [bezierPath addCurveToPoint:CGPointMake(300, 150) controlPoint1:CGPointMake(75, 0) controlPoint2:CGPointMake(225, 300)];
    //draw the path using a CAShapeLayer
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.path = bezierPath.CGPath;
    pathLayer.fillColor = [UIColor clearColor].CGColor;
    pathLayer.strokeColor = [UIColor redColor].CGColor;
    pathLayer.lineWidth = 3.0f;
    [self.redView.layer addSublayer:pathLayer];
    //add a colored layer
    CALayer *colorLayer = [CALayer layer];
    colorLayer.frame = CGRectMake(0, 0, 64, 64);
    colorLayer.position = CGPointMake(0, 150);
    colorLayer.backgroundColor = [UIColor greenColor].CGColor;
    [self.redView.layer addSublayer:colorLayer];
    
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0.0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *coverImage =  UIGraphicsGetImageFromCurrentImageContext();
    UIView *coverView = [[UIImageView alloc] initWithImage:coverImage];
    coverView.frame = self.view.bounds;
    [self.view addSubview:coverView];
    CGFloat red = arc4random() / (CGFloat)INT_MAX;
    CGFloat green = arc4random() / (CGFloat)INT_MAX;
    CGFloat blue = arc4random() / (CGFloat)INT_MAX;
    self.view.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    //perform animation (anything you like)
    [UIView animateWithDuration:1.0 animations:^{
        //scale, rotate and fade the view
        CGAffineTransform transform = CGAffineTransformMakeScale(0.01, 0.01);
        transform = CGAffineTransformRotate(transform, M_PI_2);
        coverView.transform = transform;
        coverView.alpha = 0.0;
    } completion:^(BOOL finished) {
        //remove the cover view now we're finished with it
        [coverView removeFromSuperview];
    }];
    
    /***** 2 animation group *****/
    /*
     //create the position animation
     CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animation];
     animation1.keyPath = @"position";
     animation1.path = bezierPath.CGPath;
     animation1.rotationMode = kCAAnimationRotateAuto;
     
     //create the color animation
     CABasicAnimation *animation2 = [CABasicAnimation animation];
     animation2.keyPath = @"backgroundColor";
     animation2.toValue = (__bridge id)[UIColor redColor].CGColor;
     
     //create group animation
     CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
     groupAnimation.animations = @[animation1, animation2];
     groupAnimation.duration = 4.0;
     //add the animation to the color layer
     [colorLayer addAnimation:groupAnimation forKey:nil];
     */
    
    /*******************1  keyAnimation ****************/
    /*
     //add the ship
     CALayer *shipLayer = [CALayer layer];
     shipLayer.frame = CGRectMake(0, 0, 64, 64);
     shipLayer.position = CGPointMake(0, 150);
     shipLayer.contents = (__bridge id)[UIImage imageNamed: @"右后黑"].CGImage;
     [self.redView.layer addSublayer:shipLayer];
     //create the keyframe animation
     //    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
     //    animation.keyPath = @"position";
     //    animation.duration = 4.0;
     //    animation.path = bezierPath.CGPath;
     //    animation.rotationMode = kCAAnimationRotateAuto;
     //    [shipLayer addAnimation:animation forKey:nil];
     CABasicAnimation *animation = [CABasicAnimation animation];
     animation.keyPath = @"transform.rotation";
     animation.duration = 2.0;
     animation.byValue = @(M_PI * 2);;
     [shipLayer addAnimation:animation forKey:nil];
     */
}

- (IBAction)buttonAction:(id)sender
{
    
    CFTimeInterval duration = 2;
    float repeatCount = 3;
    //animate the ship rotation
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation";
    animation.duration = duration;
    animation.repeatCount = repeatCount;
    animation.byValue = @(M_PI * 2);
    animation.delegate = self;
    [self.colorLayer addAnimation:animation forKey:@"rotateAnimation"];
    //disable controls
    [self setControlsEnabled:NO];
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //reenable controls
    [self setControlsEnabled:YES];
}
- (void)setControlsEnabled:(BOOL)enabled
{
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //get the touch point
    CGPoint point = [[touches anyObject] locationInView:self.view];
    if ([self.colorLayer.presentationLayer hitTest:point]) {
        //randomize the layer background color
        CGFloat red = arc4random() / (CGFloat)INT_MAX;
        CGFloat green = arc4random() / (CGFloat)INT_MAX;
        CGFloat blue = arc4random() / (CGFloat)INT_MAX;
        self.colorLayer.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
    }else{
        //otherwise (slowly) move the layer to new position
        [CATransaction begin];
        [CATransaction setAnimationDuration:4.0];
        self.colorLayer.position = point;
        [CATransaction commit];
    }
}

@end
